package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.model.ListPartsRequest;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-20
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Resource
    private IoTDAClient client;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    private final String IOT_ALL_PRODUCT_LIST = "iot:all_produc";

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public void updateDevice(Device device)
    {
        //调用华为云删除设备
        UpdateDeviceRequest request =  new UpdateDeviceRequest();
        UpdateDevice updateDevice = new UpdateDevice();
        request.setDeviceId(device.getIotId());
        request.setBody(updateDevice.withDeviceName(device.getDeviceName()));
        try {
            client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用iot平台失败");
        }
        //删除数据库设备
        updateById(device);

    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listPartsRequest = new ListProductsRequest();
        //设置条数
        listPartsRequest.setLimit(50);
        //发送请求
        ListProductsResponse response = client.listProducts(listPartsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new RuntimeException("物联网接口-查询产品，同步失败");
        }
        //存储到Redis
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()), 60 * 60 * 24 + (int) Math.random() * 100, TimeUnit.SECONDS);
    }

    /**
     * 查询所有产品信息
     * @return
     */

    @Override
    public List<ProductVo> AllProduct() {
        //从redis中获取产品信息
        String products = redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST);
        //如果数据为空返回一个空集合
        if(StringUtils.isEmpty(products)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(products, ProductVo.class);
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //1.判断设备名称是否存在，是则结束
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(Device::getDeviceName,dto.getDeviceName());

        if(count(deviceLambdaQueryWrapper)>0){
            throw new BaseException("注册设备失败：设备名称 【" + dto.getDeviceName() + "】 重复");
        }
        //2.设备的标识码是否已存在，是则结束
        //2.1清除mp的条件构造器
        deviceLambdaQueryWrapper.clear();
        deviceLambdaQueryWrapper.eq(Device::getNodeId,dto.getNodeId());
        if(count(deviceLambdaQueryWrapper)>0){
            throw new BaseException("注册设备失败：设备标识码 【" + dto.getNodeId() + "】 重复");
        }
        //3.是否绑定了同一个老人，是则结束
        deviceLambdaQueryWrapper.clear();
        deviceLambdaQueryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation())
                .eq(Device::getLocationType,dto.getLocationType())
                .eq(Device::getPhysicalLocationType,dto.getPhysicalLocationType())
                .eq(Device::getProductKey,dto.getProductKey());
        if(count(deviceLambdaQueryWrapper)>0){
            throw new BaseException("注册设备失败：同一位置绑定了相同的产品");
        }
        //4.注册设备，调用华为云接口注册
        //4.1请求参数addDeviceRequest对象组装
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        //设置请求体参数对象addDevice
        AddDevice addDevice = new AddDevice();
        addDevice.withNodeId(dto.getNodeId()).withProductId(dto.getProductKey()).withDeviceName(dto.getDeviceName());
        //实例AuthInfo对象，封装secret码
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        //将addDevice对象设置进AuthInfo对象中
        addDevice.withAuthInfo(authInfo);
        //AddDeviceRequest对象封装AddDevice对象（withBody）
        addDeviceRequest.withBody(addDevice);
        //4.执行请求，获取返回结果
        AddDeviceResponse response= null;
        try {
           response = client.addDevice(addDeviceRequest);
        }catch (Exception e){
            throw new BaseException("设备注册失败"+e.getMessage());
        }
        //判断响应状态
        if (response.getHttpStatusCode()!=201){
            throw new BaseException("物联网平台-注册设备失败");
        }
        //提示成功
        //5，，将前端数据DTO拷贝给Device对象
        Device device = BeanUtil.toBean(dto, Device.class);
        //补全数据
        device.setIotId(response.getDeviceId());
        //secret
        device.setSecret(secret);
        //判断是否为随身设备，物理地址为-1
        if(device.getLocationType()==0){
            device.setPhysicalLocationType(-1);
        }
        //插入数据库
        try {
            save(device);
        }catch (Exception e){
            throw new BaseException("注册失败：原因"+e.getMessage());
        }
    }

    /**
     * 查询产品信息
     * @param productKey
     * @return
     */
    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }



    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDeviceByiotId(String iotId) {
        //1.调用华为云接口删除设备
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceId(iotId);
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("调用iot平台，删除失败");
        }
        //2.调用删除数据库数据
        deviceMapper.delete(new QueryWrapper<Device>().eq("iot_id", iotId));


    }

    /**
     * 查看设备影子最新上报的数据
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);

    }
    @Override
    public AjaxResult queryServiceProperty(String iotId) {
        //1.定义返回数据对象List<Map<String,Object>>用于封装返回
        List<Map<String,Object>> data = new ArrayList<>();

        //2.远程调用IOT查询设备影子上报数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = null;
        try {
            response = client.showDeviceShadow(request);
        }catch(Exception e){
            log.error("查询华为IOT设备影子失败："+e.getMessage());
            return AjaxResult.error("查询设备数据失败");
        }

        if(response.getHttpStatusCode() != 200) {
            log.error("查询华为IOT设备影子失败");
            return AjaxResult.error("查询设备数据失败");
        }

        // 检查是否有影子数据
        if (CollUtil.isEmpty(response.getShadow())) {
            return AjaxResult.success(Collections.emptyList());
        }

        //3.解析设备影子数据，封装到List<Map<String,Object>>中
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        if(ObjectUtil.isNotEmpty(reported)){
            Object propertiesObj = reported.getProperties();
            if(propertiesObj instanceof LinkedHashMap) {
                LinkedHashMap<String,Object> properties = (LinkedHashMap<String,Object>) propertiesObj;
                String eventTimeStr = reported.getEventTime();

                properties.forEach((key,value)->{
                    // 数据完整性检查，确保key和value不为null
                    if (key == null) {
                        log.warn("跳过无效数据项，key为null，设备ID: {}", iotId);
                        return;
                    }

                    Map<String,Object> map = new HashMap<>();
                    map.put("functionId", key);
                    // 确保value不为null，为null时设置默认值
                    map.put("value", value != null ? value : "");

                    // 增强的时间解析逻辑，支持多种格式
                    String formattedTime = parseEventTime(eventTimeStr, iotId, key);
                    map.put("eventTime", formattedTime);

                    //将map添加到List<Map<String,Object>>中
                    data.add(map);
                });
            }
        }
        //4.封装AjaxResult返回
        return AjaxResult.success(data);
    }

    /**
     * 解析事件时间，支持多种格式，确保返回一致的时间格式
     * @param eventTimeStr 原始时间字符串
     * @param iotId 设备ID（用于日志）
     * @param functionId 功能ID（用于日志）
     * @return 格式化后的时间字符串 "2025-01-28 15:30:45"
     */
    private String parseEventTime(String eventTimeStr, String iotId, String functionId) {
        // 如果时间字符串为空，返回当前时间
        if (StrUtil.isEmpty(eventTimeStr)) {
            log.debug("事件时间为空，使用当前时间，设备ID: {}, 功能ID: {}", iotId, functionId);
            return LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }

        LocalDateTime eventTime = null;

        try {
            // 尝试多种时间格式解析
            if (eventTimeStr.length() == 16 && eventTimeStr.charAt(15) == 'Z') {
                // 不带毫秒格式: yyyyMMdd'T'HHmmss'Z' 如：20250128T153045Z
                eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            } else if (eventTimeStr.length() == 20 && eventTimeStr.charAt(19) == 'Z') {
                // 带毫秒格式: yyyyMMdd'T'HHmmss.SSS'Z' 如：20250128T153045.123Z
                eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss.SSS'Z'");
            } else if (eventTimeStr.contains("-") && eventTimeStr.contains("T") && eventTimeStr.endsWith("Z")) {
                // ISO 8601格式: yyyy-MM-dd'T'HH:mm:ss'Z' 如：2025-01-28T15:30:45Z
                try {
                    ZonedDateTime zonedDateTime = ZonedDateTime.parse(eventTimeStr);
                    eventTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
                } catch (Exception e) {
                    // 如果ZonedDateTime解析失败，尝试LocalDateTime解析
                    eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyy-MM-dd'T'HH:mm:ss'Z'");
                }
            } else if (eventTimeStr.contains("-") && eventTimeStr.contains(":")) {
                // 标准格式: yyyy-MM-dd HH:mm:ss 如：2025-01-28 15:30:45
                eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyy-MM-dd HH:mm:ss");
            } else {
                // 默认尝试华为IoT常用格式
                eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            }

            // 如果解析成功且原始时间是UTC时间（以Z结尾），进行时区转换
            if (eventTime != null && eventTimeStr.endsWith("Z") && !eventTimeStr.contains("-")) {
                eventTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
            }

        } catch (Exception e) {
            log.warn("时间解析失败，使用当前时间，设备ID: {}, 功能ID: {}, 原始时间: {}, 错误: {}",
                    iotId, functionId, eventTimeStr, e.getMessage());
            // 解析失败时使用当前时间
            eventTime = LocalDateTime.now();
        }

        // 确保eventTime不为null，并格式化为统一格式
        if (eventTime == null) {
            eventTime = LocalDateTime.now();
        }

        return eventTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }



    /**
     * 查询设备最新上报影子数据
     *
     * @param iotId
     * @return
     */
    // @Override
    // public AjaxResult queryServiceProperties(String iotId) {
    //
    //     //1.定义返回数据对象List<Map<String,Object>>用于封装返回
    //     List<Map<String,Object>> data = new ArrayList<>();
    //
    //     //2.远程调用IOT查询设备影子上报数据
    //     ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
    //     request.withDeviceId(iotId);
    //     ShowDeviceShadowResponse response = null;
    //     try {
    //         response = client.showDeviceShadow(request);
    //     }catch(Exception e){
    //         log.error("查询华为IOT设备影子失败："+e.getMessage());
    //         e.printStackTrace();
    //         throw new RuntimeException("查询华为IOT设备影子失败："+e.getMessage());
    //     }
    //     if(response.getHttpStatusCode() != 200) {
    //         log.error("查询华为IOT设备影子失败");
    //         throw new RuntimeException("查询华为IOT设备影子失败");
    //     }
    //     //3.解析设备影子数据，封装到List<Map<String,Object>>中
    //     DeviceShadowProperties reported = response.getShadow().get(0).getReported();
    //     if(ObjectUtil.isNotEmpty(reported)){
    //         LinkedHashMap<String,Object> properties = (LinkedHashMap<String,Object>)reported.getProperties();
    //         properties.forEach((key,value)->{
    //             Map<String,Object> map = new HashMap<>();
    //             map.put("functionId",key);
    //             map.put("value",value);
    //
    //             String eventTimeStr = reported.getEventTime();
    //             if(StrUtil.isNotEmpty(eventTimeStr)) {
    //
    //                 LocalDateTime eventTime =  LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
    //                 //日期时区转换
    //                 //日期时区转换
    //                 eventTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
    //                         .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
    //                         .toLocalDateTime();
    //                 map.put("eventTime",eventTime);
    //             }
    //             //将map添加到List<Map<String,Object>>中
    //             data.add(map);
    //         });
    //     }else{
    //         return AjaxResult.warn("暂无最新上报数据");
    //     }
    //
    //     //4.封装AjaxResult返回
    //     return AjaxResult.success(data);
    // }

    /**
     * 根据id查询设备详细信息
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //从数据库查询设备信息
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response ;
        try {
            response = client.showDevice(request);
        }catch (Exception e){
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        //属性拷贝
        DeviceDetailVo detailVo=BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            // 使用 ZonedDateTime 解析带时区的 ISO8601 格式
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(activeTimeStr);
            // 转换为上海时区的 LocalDateTime
            LocalDateTime activeTime = zonedDateTime
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setActiveTime(activeTime);
        }
        return detailVo;

    }
    /**
     * 查询设备详情
     *
     * @return
     */


    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id)?1:0;
    }

}
